import WSocket from '@/utils/web-socket';
import tool from '@/utils/tool';

class Message {
  ws;
  timer = null;
  interval = 10 * 1000;
  constructor() {
    const { protocol } = document.location;
    let httpUrl = '';
    if (protocol === 'http:') {
      httpUrl = 'ws:' + import.meta.env.VITE_APP_WS_URL;
    } else {
      httpUrl = 'wss:' + document.location.hostname + '/websocket';
      // 服务器配置
      // location /websocket {
      //   proxy_pass http://127.0.0.1:9502/websocket;
      //   proxy_http_version 1.1;
      //   proxy_set_header Upgrade $http_upgrade;
      //   proxy_set_header Connection "upgrade";
      // }
    }
    this.ws = new WSocket(
        httpUrl + '?token=' + tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX), {
          onOpen:  _ => {
            console.log('已成功连接到消息服务器...');
          },
          onError: _ => {
            this.ws = undefined;
            console.log('未成功连接到消息服务器...');
          },
          onClose: _ => {
            this.ws = undefined;
            console.log('与消息服务器断开...');
          },
        }
    );
    // 关闭心跳数据包
    this.ws.heartbeat.openHeartbeat = false;
  };

  getMessage() {
    this.timer = setInterval(() => {
      this.ws && this.ws.send({
        event: 'get_unread_message',
        token: tool.local.get(import.meta.env.VITE_APP_TOKEN_PREFIX),
      });
    }, this.interval);
  };
  connection() {
    this.ws.connection();
  };
}

export default Message;